package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.DeviceIotEnum;
import com.itlong.cloud.iot.service.base.IotBaseService;
import com.itlong.cloud.sms.SmsMsgService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *  <desc>
 *       发布消息至iot中心topic
 *  </desc>
 *
 * @createDate 2018/04/11
 */
@Component
public class PubIotMessageConsumer04 {
    private static final Logger LOG = LoggerFactory.getLogger(DeviceIotConsumer.class);

    @Autowired
    IotBaseService iotBaseService;

    @Autowired
    SmsMsgService smsMsgService;

    /**
     * <desc>
     *     云电梯设备信息同步至IOT消费端
     * </desc>
     *
     * @param message
     * @param channel
     * @throws InterruptedException
     * @throws IOException
     * @author Jiaqi.X
     * @createDate 2018/04/11
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_IOT_PUB_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException, IOException {
        byte[] body = message.getBody();
        LOG.info("RabbitMQ_消费者4_发布消息至iot中心topic:"+new String(body));
        try {
            boolean flag = false;
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JSON.parseObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            JSONObject js = JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent());
            String data = js.getString("data");
            JSONObject jsonObject = JSONObject.parseObject(data);
            //如果消费的时间和生产的时间间隔时间长则报警
            if (jsonObject.containsKey("timestamp")) {
                long inTime = jsonObject.getLong("timestamp");
                long outTime = (new Date()).getTime();
                if (outTime - inTime >= 1000) {
                    LOG.error("【消费消息不及时】{} {}", outTime - inTime, data);
                    //smsMsgService.sendSmsCodeByEmail("xxfaxy@qq.com", "[消费消息不及时]" + data);
                    //smsMsgService.sendSmsCodeByEmail("zhouc@itlong.com.cn", "[消费消息不及时]" + data);
                }
            }
            Integer deviceElevatorOperateIotType = jsonObject.getInteger("deviceOperateIotType");
            if(deviceElevatorOperateIotType == DeviceIotEnum.PUB_MESSAGE.getCommandType()) {
                List<Map<String,Object>> messages = JsonUtil.decode(jsonObject.getString("devices"), new TypeReference<List<Map<String, Object>>>() {});
                messages.forEach(mes->{
                    //发布控制指令到iot中心具体设备（异步）
                    iotBaseService.pubDeviceMessage(mes.get("productKey").toString(),mes.get("topic").toString(),mes.get("message").toString(),
                            StringHandlerUtil.getNullOrStringForObject(mes.get("huaweiIotMessage")),StringHandlerUtil.getNullOrStringForObject(mes.get("serviceId")),
                            StringHandlerUtil.getNullOrStringForObject(mes.get("commandName")),StringHandlerUtil.getNullOrStringForObject(mes.get("iotFlag")));
                });
            }
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_消费者4_发布消息至iot中心topic】:解析异常",e);
        }finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            LOG.info("RabbitMQ_消费者4_确认消息 {}", new String(body));
        }
    }
}
